package com.market.cash.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.market.cash.R
import com.market.cash.configs.CashRootConfigs
import com.market.cash.databinding.CashOrderDetailsBinding
import com.market.cash.pro.ProActivity
import com.market.cash.ui.adapter.CashRootOrderDetailsAccountAdapter
import com.market.cash.ui.presenter.CashRootOrderDetailsPresenter
import com.market.cash.ui.view.ICashRootOrderDetailsView
import com.market.cash.utils.CashRootDensityUtil
import com.market.cash.utils.CashRootImageUtil
import com.market.cash.utils.decoration.LinearSpacingItemDecoration
import com.market.cash.utils.dialog.CashRootBindCardDeleteDialog
import com.market.cash.utils.dialog.CashRootBindCardDialog
import com.market.cash.utils.dialog.CashRootBindCardOtherDialog
import com.market.cash.utils.dialog.CashRootNoticeDialog
import com.market.cash.utils.event.CashRootEventData
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import com.market.cash.utils.helper.SharedHelper
import org.json.JSONArray
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/28 14:01
 * @Annotation：贷款订单详情
 */
class OrderDetailsActivity: ProActivity(), ICashRootOrderDetailsView {
    lateinit var binding: CashOrderDetailsBinding
    var presenter: CashRootOrderDetailsPresenter? = null

    //账户列表
    private var accountAdapter: CashRootOrderDetailsAccountAdapter? = null
    //埋点备注
    var eventRemark = ""

    companion object {
        private const val INTENT_KEY_LOGO = "logo"
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        private const val INTENT_KEY_TITLE = "title"
        fun start(context: Context,pLogo: String, pName: String, pToken: String,pTitle: String) {
            val intent = Intent(context, OrderDetailsActivity::class.java)
            intent.putExtra(INTENT_KEY_LOGO, pLogo)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            intent.putExtra(INTENT_KEY_TITLE, pTitle)
            context.startActivity(intent)
        }
    }

    override fun getCashRootRootView(): View {
        binding = CashOrderDetailsBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initCashRootView() {
        setCashRootTitleBarVisibility(View.VISIBLE)
        setCashRootTitleBarColor(Color.parseColor("#FFFFFFFF"))
        setCashRootBackBtnRes(R.mipmap.cash_back_black)
        setCashRootRightBtnRes(R.mipmap.cash_kefu_black)
        setCashRootTextTitle(getString(R.string.order_status_title))

        initCashRootRefreshLayout()
        initCashRootRecyclerViews()
        binding.parentLayout.visibility = View.GONE
    }

    override fun initCashRootListener() {
        //客服
        rootViewBinding.imgKefu.setOnClickListener {
            KefuActivity.start(this,eventRemark,loadPName(),loadPToken())
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_CUSTOMER,eventRemark)
        }
        //去申请
        binding.btnOk.setOnClickListener {
            publishEventData(CashRootEventData(CashRootEventData.TYPE.CASHROOT_SHOW_HOME))
            finish()
        }

        //添加账户
        binding.btnAdd.setOnClickListener {
            showCashRootBinCardAddDialog()
        }
    }

    override fun initCashRootData() {
        presenter = CashRootOrderDetailsPresenter(this)
        showCashRootLoading()
        presenter!!.loadCashRootOrderStatusAction()

        //牌照信息
        if (!CashRootCustomConfigsHelper.isCashRootShowLicense()){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(initCashRootLicenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }


    /* 初始化刷新 */
    private fun initCashRootRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            presenter!!.loadCashRootOrderStatusAction()
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 初始化Views
     */
    private fun initCashRootRecyclerViews(){
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val topDecoration = CashRootDensityUtil.dp2px(12f)
        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0, 0, 0, topDecoration))
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.recyclerView.layoutManager = layoutManager
        accountAdapter = CashRootOrderDetailsAccountAdapter(binding.recyclerView)
        binding.recyclerView.adapter = accountAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        accountAdapter!!.setOnItemChildClickListener { _, childView, position ->
            val item = accountAdapter!!.getItem(position)
            when(childView.id){
                R.id.imgDelete -> {//删除
                    showCashRootDeleteDialog(item)
                }
            }
        }
    }

    /**
     * 产品Logo
     */
    private fun loadPLogo(): String{
        return intent.extras!!.getString(INTENT_KEY_LOGO).toString()
    }

    /**
     * 获取查看的产品名称
     */
    override fun loadPName(): String {
        return intent.extras!!.getString(INTENT_KEY_PRODUCT).toString()
    }

    /**
     * 获取查看的产品Token
     */
    override fun loadPToken(): String {
        return intent.extras!!.getString(INTENT_KEY_TOKEN).toString()
    }

    /**
     * 获取产品Title
     */
    private fun loadPTitle(): String {
        return intent.extras!!.getString(INTENT_KEY_TITLE).toString()
    }

    /**
     * 共用Views
     */
    @SuppressLint("SetTextI18n")
    override fun showCashRootOrderCommonViews(obj: JSONObject) {
        binding.parentLayout.visibility = View.VISIBLE
        CashRootImageUtil.instance.loadImageUrl(this,binding.imgLogo,loadPLogo(), R.mipmap.cash_holder)
        binding.textName.text = loadPTitle()
        binding.textAmount.text = "${obj.optString("currency")} ${obj.optString("amount")}"
        binding.textTerm.text = String.format(getString(R.string.loan_term_value),obj.optString("days"))
    }

    /**
     * 审核中
     */
    override fun showCashRootOrderAuditViews(obj: JSONObject) {
        binding.imgStatusIcon.setImageResource(R.mipmap.cash_pin_status_process)

        val showKey = getString(R.string.loan_details_audit_tips_key)
        val showText = String.format(getString(R.string.loan_details_audit_tips),showKey)
        val startIndex = showText.indexOf(showKey)

        val spString = SpannableString(showText)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FF4D3E")), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textStatusTips.text = spString

        binding.textDisburse.visibility = View.GONE
        binding.recyclerView.visibility = View.GONE
        binding.btnAdd.visibility = View.GONE
        binding.auditLayout.visibility = View.VISIBLE
        binding.applyTipsLayout.visibility = View.GONE//去申请提示

        //是否存在可申请的产品
        val pData = SharedHelper.getCashRootSPString(SharedHelper.CashRoot_SPKEY.CASHROOT_PRODUCT)
        var isContainsApply = false
        if (pData.isNotEmpty()){
            val objArray = JSONArray(pData)
            for (i in 0..<objArray.length()){
                val item = objArray.optJSONObject(i)
                val status = item.optString("status")
                val activeFlag = item.optString("activeFlag")
                val applyStatus = item.optString("applyStatus")
                //可申请
                if (activeFlag == "YES" && status == "APPLY" && !applyStatus.endsWith("DENIED")){
                    isContainsApply = true
                    break
                }
            }
        }
        if (isContainsApply){
            binding.applyTipsLayout.visibility = View.VISIBLE
        }




        //根据配置显示公告信息
        showCashRootLoanNoticeDialog()
        //需要调用评分接口
        presenter!!.loadCashRootScoreCommentAction()
    }

    /**
     * 放款中
     */
    override fun showCashRootOrderLendingViews(obj: JSONObject) {
        binding.imgStatusIcon.setImageResource(R.mipmap.cash_pin_status_success)

        val showKey = getString(R.string.loan_details_lending_tips_key)
        val showText = String.format(getString(R.string.loan_details_lending_tips),showKey)
        val startIndex = showText.indexOf(showKey)

        val spString = SpannableString(showText)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#100437")), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textStatusTips.text = spString

        binding.textDisburse.visibility = View.VISIBLE
        binding.recyclerView.visibility = View.VISIBLE
        binding.auditLayout.visibility = View.GONE

        //根据配置显示公告信息
        showCashRootLoanNoticeDialog()
        //需要显示账户列表
        presenter!!.loadCashRootBindCardListAction()
        //需要调用评分接口
        presenter!!.loadCashRootScoreCommentAction()

        binding.btnAdd.visibility = View.GONE
        //法语地区显示添加账户按钮
        if (CashRootConfigs.isFrench()){
            binding.btnAdd.visibility = View.VISIBLE
        }
    }

    /**
     * 已拒绝
     */
    override fun showCashRootOrderRejectedViews(obj: JSONObject) {
        binding.imgStatusIcon.setImageResource(R.mipmap.cash_pin_status_failed)

        val showKey = String.format(getString(R.string.loan_details_rejected_tips_key),obj.optString("againApplyDate"))
        val showText = String.format(getString(R.string.loan_details_rejected_tips),loadPTitle(),showKey)
        val startIndex = showText.indexOf(showKey)

        val spString = SpannableString(showText)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#100437")), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textStatusTips.text = spString

        binding.textDisburse.visibility = View.GONE
        binding.recyclerView.visibility = View.GONE
        binding.btnAdd.visibility = View.GONE
        binding.auditLayout.visibility = View.GONE
    }

    /**
     * 待还款
     */
    override fun showCashRootOrderRepayViews(obj: JSONObject) {
        //跳转到待还款列表
        publishEventData(CashRootEventData(CashRootEventData.TYPE.CASHROOT_SHOW_REPAY))

        Handler(Looper.getMainLooper()).postDelayed({
            //刷新产品列表
            publishEventData(CashRootEventData(CashRootEventData.TYPE.CASHROOT_PRODUCT_REFRESH))
            finish()
        },1000)
    }

    /**
     * 收款账户列表
     */
    override fun showCashRootBindCardList(accountList: ArrayList<JSONObject>) {
        accountAdapter!!.data = accountList

        //最多添加10个账户
        if (accountAdapter!!.itemCount >= 10){
            binding.btnAdd.isEnabled = false
        } else {
            binding.btnAdd.isEnabled = true
        }
    }

    /**
     * 添加绑卡dialog
     */
    private fun showCashRootBinCardAddDialog(){
        addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_USER_ACCOUNT_ADD,eventRemark)
        val bindCardDialog = CashRootBindCardDialog(this,eventRemark,object : CashRootBindCardDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                presenter!!.submitCashRootBindAccountAction(phoneNumber,typeObj.optString("value"))
            }
        })
        bindCardDialog.setCancelable(true)
        bindCardDialog.setCanceledOnTouchOutside(true)
        bindCardDialog.show()
    }

    /**
     * 提示绑定另一个渠道账户
     */
    override fun showCashRootBindCardOtherDialog(otherInfo: JSONObject) {
        val replaceDialog = CashRootBindCardOtherDialog(this,eventRemark,object : CashRootBindCardOtherDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.btnConfirm){//添加
                    presenter!!.submitCashRootBindAccountAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                }
            }
        })
        replaceDialog.setCancelable(true)
        replaceDialog.setCanceledOnTouchOutside(false)
        replaceDialog.show()
        replaceDialog.setBindAccountInfo(otherInfo)
    }

    /**
     * 删除提示
     */
    private fun showCashRootDeleteDialog(item: JSONObject){
        item.put("walletLogo",item.optString("logo"))
        item.put("walletDesc",item.optString("name"))
        item.put("walletMobile",item.optString("account"))
        addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_USER_ACCOUNT_DELETE,item.optString("cardId"))
        val deleteDialog = CashRootBindCardDeleteDialog(this,eventRemark, object : CashRootBindCardDeleteDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.btnSubmit){
                    presenter!!.deleteCashRootAccountAction(item.optString("cardId"))
                }
            }
        })
        deleteDialog.setCancelable(true)
        deleteDialog.setCanceledOnTouchOutside(true)
        deleteDialog.show()
        deleteDialog.setBindAccountInfo(item)
    }

    /**
     * 审核中、放款中 根据配置显示公告Dialog
     */
    private fun showCashRootLoanNoticeDialog(){
        if (!CashRootCustomConfigsHelper.isCashRootAuditNotice()){
            return
        }

        val noticeInfo = CashRootCustomConfigsHelper.getCashRootAuditNoticeInfo() ?: return
        val showNum = noticeInfo.optInt("num",1)
        val completeNum = SharedHelper.getCashRootSPInt(SharedHelper.CashRoot_SPKEY.CASHROOT_DIALOG_NOTICE_NUM)
        //本地记录的显示公告次数 >= 配置次数
        if (completeNum >= showNum){
            return
        }

        SharedHelper.saveCashRootSPData(SharedHelper.CashRoot_SPKEY.CASHROOT_DIALOG_NOTICE_NUM,completeNum+1)
        val noticeDialog = CashRootNoticeDialog(this,object : CashRootNoticeDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
        })
        noticeDialog.show()
        noticeDialog.setTipsTitle(noticeInfo.optString("noticeTitle"))
        noticeDialog.setTips(noticeInfo.optString("noticeText"))
    }

    override fun hideCashRootLoading() {
        super.hideCashRootLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        eventRemark = "${loadPName()} Details Page"
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_LOAN_DETAILS_START,eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_LOAN_DETAILS_END,eventRemark)
    }
}